<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/29
 * Time: 16:38
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForBiddenException;
use app\lib\exception\NotFoundException;
use think\facade\Cache;
use think\Exception;
use think\Request;

class TokenService
{

    // 生成令牌
    public static function generateToken()
    {
        $randChar = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = config('secure.token_salt');
        return md5($randChar . $timestamp . $tokenSalt);
    }


    public static function getTokenVar($key){
        $request = new Request();
        $token = $request->header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new NotFoundException([
                'msg'=>'Token已经失效或过期'
            ]);
        }
        if(!is_array($vars)){
            $vars = json_decode($vars,true);
        }


        if(array_key_exists($key,$vars)){
            return $vars[$key];
        }else{
            throw new Exception('token变量不存在');
        }
    }

    public static function getCurrentUid(){
        return self::getTokenVar('uid');
    }

    public static function checkPrimaryScope(){
        $scope = self::getTokenVar('scope');
        if(!$scope){
            throw new NotFoundException([
                'msg'=>'Token已经失效或过期'
            ]);
        }
        if($scope>=ScopeEnum::User){
            return true;
        }else{
            throw new ForBiddenException();
        }
    }

    public static function checkExcluteScope(){
        $scope = self::getTokenVar('scope');
        if(!$scope){
            throw new NotFoundException([
                'msg'=>'Token已经失效或过期'
            ]);
        }
        if($scope>=ScopeEnum::User){
            return true;
        }else{
            throw new ForBiddenException();
        }
    }

    public static function isValidOperate($uid){
        return $uid==self::getCurrentUid()?true:false;
    }

}